﻿using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using Microsoft.Playwright;
using ModelContextProtocol.Server;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MCPSSETest.Tools
{
    [McpServerToolType]
    public sealed class PlayWrightTool
    {

        [McpServerTool(Name = "ScreenShotUrl"), Description("打开一个页面,截图返回这个页面")]
        public static async Task<byte[]> ScreenShotUrl(
        IMcpServer thisServer,
        [Description("Open a url page")] string url,
        CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException("URL不能为空", nameof(url));
            }

            // 初始化Playwright
            using var playwright = await Playwright.CreateAsync();

            // 启动浏览器(Chromium)
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = true, // 无头模式
                Timeout = 30000   // 30秒超时
            });
 
            // 创建新页面
            var page = await browser.NewPageAsync();

            try
            {
                // 设置默认视口大小(可选)
                await page.SetViewportSizeAsync(1920, 1080);

                // 导航到目标URL
                var response = await page.GotoAsync(url, new PageGotoOptions
                {
                    WaitUntil = WaitUntilState.NetworkIdle, // 等待网络空闲
                    Timeout = 30000 // 30秒超时
                });

                if (response == null || !response.Ok)
                {
                    throw new Exception($"无法访问URL: {url}. 状态码: {response?.Status}");
                }

                // 设置默认截图选项(如果未提供)
                var screenshotOptions = new PageScreenshotOptions
                {
                    FullPage = true,        // 截取完整页面
                    Type = ScreenshotType.Jpeg, // PNG格式
                    Quality = 90,             // 图片质量(仅对JPEG有效)
                    Timeout = 30000          // 30秒超时
                };

                // 执行截图并返回二进制数据
                return await page.ScreenshotAsync(screenshotOptions);
            }
            catch (Exception ex)
            {
                throw new Exception($"截图过程中发生错误: {ex.Message}", ex);
            }
            finally
            {
                // 确保关闭页面
                await page.CloseAsync();
            }
        }


        [McpServerTool(Name = "InitiationProcess"), Description("发起流程")]
        public static async Task<string> InitiationProcess(
            [Description("process name")] string name,
            [Description("data")] string jObjectData)
        {

            using var playwright = await Playwright.CreateAsync();

            // 启动浏览器(非无头模式)
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false // 可视化浏览器窗口
            });

            // 创建新页面
            var page = await browser.NewPageAsync();

            try
            {
                // 打开登录页面
                await page.GotoAsync("https://admin.tgmohe.com");
                await page.WaitForTimeoutAsync(5000);

                // 输入账号和密码
                await page.FillAsync("input[id=\"form_item_phoneNumber\"]", "16638640391");
                await page.WaitForTimeoutAsync(5000);
                await page.FillAsync("input[id=\"form_item_password\"]", "xxxxx");

                // 点击登录按钮
                await page.GetByRole(AriaRole.Button, new PageGetByRoleOptions { Name = "登 录" }).ClickAsync();

                // 点击"开发测试"菜单
                await page.GetByTitle("开发测试").ClickAsync();

                if (name == "工作总结")
                {
                    // 等待导航完成
                    await page.WaitForURLAsync(url => url.Contains("dashboard"), new PageWaitForURLOptions
                    {
                        Timeout = 30000
                    });

                    // 在搜索框中输入"发起流程"并回车
                    var searchBox = page.GetByRole(AriaRole.Combobox, new PageGetByRoleOptions { Name = "" });
                    await searchBox.FillAsync("发起流程");
                    await searchBox.PressAsync("Enter");

                    // 点击"工作总结"
                    await page.GetByText("工作总结", new PageGetByTextOptions { Exact = true }).ClickAsync();
                    await page.WaitForTimeoutAsync(5000);


                    var obj = JObject.Parse(jObjectData);

                    await page.Locator("#form_item_title").FillAsync(obj["title"].ToString());
                    await page.GetByText("提 交", new() { Exact = true }).ClickAsync();

                }

                return "ok";
            }
            catch(Exception ex)
            {
                Console.WriteLine($"自动化操作过程中发生错误: {ex.Message}");
                throw;
            }
            finally
            {
                // 关闭页面
                await page.CloseAsync();
            }
        }
    }
}
